#!/usr/bin/perl

use Scalar::Util qw(looks_like_number);

use strict;

my $list;
my $count = 0;

my @cols = ("barcode", "current_center", "sampling_center", "rsid", "gender", "specimen_type", "visit_num", "volume", "ctr_volume", "ng_per_ul", "in_library_construction", "ii_seq_june_2012");

my $body_site_column = 5;
my $barcode_column = 0;

my @key_sites = ("Stool", "Tongue dorsum", "Supragingival plaque", "Buccal mucosa", "Anterior nares", "Posterior fornix");

my ($exclude, $ex_num) = load_list(@ARGV[0]);
my $done;

my $count = 0;

while(<STDIN>) {
  s/\n//;
  my $i = 0;

  my @data = split(/\t/);
  my $site = $data[$body_site_column];
  my $rsid = $data[$barcode_column];

  foreach my $s (@key_sites) {
      if ($exclude->{$rsid} == 1 && $site =~ /$s/) {
	  foreach my $j (@data) {
	      $list->{$count}->{$cols[$i]} = $j;
	      $i++
	  }
	  # changes tag to one in body site list
	  $list->{$count}->{'specimen_type'} = $s; 
	  $count++;
	  $done->{$rsid} = 1;
      }
  }
}

$list->{'count'} = $count;

my $i;

my $glist;

for($i=0;$i<$list->{'count'};$i++) {
    my $site = $list->{$i}->{'specimen_type'};
    my $gender = $list->{$i}->{'gender'};
    my $rsid = $list->{$i}->{'barcode'};
    $glist->{$site}->{$gender}++;
}

print "$count Samples Count (total completed: $ex_num) \n";
print "Body site\tGender\tCount\n";

for my $site (@key_sites) {
    print "$site\tMale\t" . $glist->{$site}->{"Male"} . "\n";
    print "$site\tFemale\t" . $glist->{$site}->{"Female"} . "\n";
}

sub assign_mass {
    my $list = shift;
    for($i=0;$i<$list->{'count'};$i++) {
	my $mass;
	if ($list->{$i}->{'ctr_volume'} eq "\#N/A") {
	    $list->{$i}->{'ctr_volume'} = "N/A";
	}
	if (looks_like_number($list->{$i}->{'ctr_volume'}) && 
	    looks_like_number($list->{$i}->{'ng_per_ul'})) {
	    $mass = $list->{$i}->{'ctr_volume'} * 
		$list->{$i}->{'ng_per_ul'};
	}
	else {
	    $mass = "N/N";
	}
	$list->{$i}->{'mass'} = $mass;
    }
}

sub load_list {
    my $file = shift;
    my $l, $count;

    open(F_IN, $file) || die ("supply an exlude list");
    while(<F_IN>) {
	s/\n//;
	$l->{$_} = 1;
	$count++;
    }

    return ($l, $count)
}

